package com.slashmobility.finappsparty.parser;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;

import com.slashmobility.finapps.model.ModelPiso;


/**
 * Parser para convertir de XML a modelo de datos
 * @author josecortes
 *
 */

public class SAXParserModelPiso {
	
	SAXParserFactory factory;
	SAXParser saxParser;
	
	private ArrayList<ModelPiso> pisos = null;
	
	public void parsePisos(Context context) throws ParserConfigurationException, SAXException, IOException {
		
		factory = SAXParserFactory.newInstance();
		saxParser = factory.newSAXParser();	
		
		pisos = new ArrayList<ModelPiso>();
		
		saxParser.parse(context.getAssets().open("test_pisos.xml"), handler);
	}

	public ArrayList<ModelPiso> getPisos() {
		return pisos;
	}

	DefaultHandler handler = new DefaultHandler() {
		String currentValue;
		ModelPiso tmpPiso = null;
		
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if(qName.equalsIgnoreCase("piso")) {
				tmpPiso = new ModelPiso();
			}
		}

		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if(qName.equalsIgnoreCase("id")) {
				tmpPiso.setId(currentValue);
			}
			
			if(qName.equalsIgnoreCase("precio")) {
				tmpPiso.setPrecio(Double.valueOf(currentValue));
			}
			
			if(qName.equalsIgnoreCase("descripcion")) {
				tmpPiso.setDescripcion(currentValue);
			}
			
			if(qName.equalsIgnoreCase("poblacion")) {
				tmpPiso.getLocalizacion().setPoblacion(currentValue);
			}
			
			if(qName.equalsIgnoreCase("direccion")) {
				tmpPiso.getLocalizacion().setDireccion(currentValue);
			}
			
			if(qName.equalsIgnoreCase("latitud")) {
				tmpPiso.getLocalizacion().setLatitud(Double.valueOf(currentValue));
			}
			
			if(qName.equalsIgnoreCase("longitud")) {
				tmpPiso.getLocalizacion().setLongitud(Double.valueOf(currentValue));
			}
			
			if(qName.equalsIgnoreCase("piso")) {
				pisos.add(tmpPiso);
			}

		}

		public void characters(char ch[], int start, int length)
				throws SAXException {
			currentValue = new String(ch, start, length);
		}
	};
}
